//
//  ToutiaoTableViewController.m
//  BobNews
//
//  Created by lanou3g on 16/5/5.
//  Copyright © 2016年 liu. All rights reserved.
//

#import "ToutiaoTableViewController.h"
#import "NetWorkRequestManager.h"
#import "MenuViewController.h"
#import "ToutiaoModel.h"

#import "ToutiaoModelCell.h"
#import "ToutiaoImageModelCell.h"
#import "ToutiaoMulImgModelCell.h"

#import "LORefresh.h"
#import "CycleView.h"

#import "ToutiaoArticleViewController.h"
#import "ToutiaoSpeciaTableController.h"
#import "ToutiaoPhotoViewController.h"

#import "BeautyTableController.h"
#import "EntertainmentController.h"
#import "JokeTableViewController.h"
#import "BJTableViewController.h"
#import "SportTableViewController.h"
#import "HotBaseController.h"
#import "SearchTableViewController.h"

/// 引导页
#import "GuideManager.h"

@interface ToutiaoTableViewController ()<MenuClickDelegate>

@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,strong) NSString *start;
@property (nonatomic,strong) NSArray *adsArray;
@property (nonatomic,strong) CycleView *cycleView;
@property (nonatomic,strong) UILabel *titleLabel;

@property (nonatomic,strong) NSString *str;

@end

@implementation ToutiaoTableViewController

- (void)dealloc {
    [self.tableView removeObserver:[self.tableView defaultHeader] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.title = @"头条";
    /// 引导页
    NSMutableArray *images = [NSMutableArray array];
    [images addObject:[[NSBundle mainBundle] pathForResource:@"427495" ofType:@"jpg"]];
    [images addObject:[[NSBundle mainBundle] pathForResource:@"9fa4451685e1e91f67fd5d4919b80003941073a150f75-FyThqd_fw658" ofType:@"jpg"]];
    [[GuideManager shared] showGuideViewWithImages:images];
    
    
    [MenuViewController getMenu].MenuDelegate = self;
    [MenuViewController getMenu].menuArray = [@[@"头条 • HEADLINES",@"娱乐 • ENTERTAINMENT",@"热点 • HOT",@"体育 • SPORTS",@"北京 • Beijing",@"美女 • BEAUTY",@"历史 • HISTORY"] mutableCopy];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"菜单.png"] style:UIBarButtonItemStylePlain target:self action:@selector(addMenu:)];
    
    self.dataSource = [NSMutableArray array];
    
    // 网络数据
    [self analyticalData];
    
    /// 注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"ToutiaoImageModelCell" bundle:nil] forCellReuseIdentifier:@"ToutiaoImageModel"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ToutiaoMulImgModelCell" bundle:nil] forCellReuseIdentifier:@"ToutiaoMulImgModel"];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    [self cycle];
    
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, 30)];
    [self.cycleView addSubview:self.titleLabel];
    self.titleLabel.textColor = [UIColor whiteColor];
    
    
    
    /// 上拉加载，下拉刷新
    self.start = @"0-20";
    [self addRefresh];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemSearch) target:self action:@selector(addSearch:)];
    
}

- (void)addSearch:(UIBarButtonItem *)sender {
    
    SearchTableViewController *SearchVC = [[SearchTableViewController alloc]init];
    SearchVC.urlStr = self.str;
    [self.navigationController pushViewController:SearchVC animated:YES];
    
    }
- (void)addMenu:(UIBarButtonItem *)sender {
    if ([MenuViewController getMenu].isShow) {
        [[MenuViewController getMenu] closeMenu];
    } else {
        [[MenuViewController getMenu] openMenu];
    }
}
- (void)cycle {
    self.cycleView = [[CycleView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200) interVal:1];
    self.tableView.tableHeaderView = self.cycleView;
}

#pragma mark - 点击菜单项的代理
- (void)didClickMenuIndex:(NSInteger)index Title:(NSString *)title {
    switch (index) {
        case 0:
        {
            self.navigationItem.title = @"头条";
        }
            break;
        case 1:
        {
            EntertainmentController *enterVC = [[EntertainmentController alloc]init];
            enterVC.title = @"娱乐";
            [self.navigationController pushViewController:enterVC animated:YES];
        }
            break;
        case 2:
        {
            HotBaseController *hotVC = [[HotBaseController alloc]init];
            hotVC.title = @"热点";
            [self.navigationController pushViewController:hotVC animated:YES];
        }
            break;
            
        case 3:
        {
            SportTableViewController *sportVC = [[SportTableViewController alloc]init];
            sportVC.title = @"体育";
            [self.navigationController pushViewController:sportVC animated:YES];
        }
            break;
            
        case 4:
        {
            BJTableViewController *beijingVC = [[BJTableViewController alloc]init];
            beijingVC.title = @"北京";
            [self.navigationController pushViewController:beijingVC animated:YES];
        }
            break;
            
            
        case 5:
        {
            BeautyTableController *beautyTVC = [[BeautyTableController alloc]init];
            beautyTVC.title = @"美女";
            [self.navigationController pushViewController:beautyTVC animated:YES];
        }
            break;
            
        case 6:
        {
            JokeTableViewController *jokeVC = [[JokeTableViewController alloc]init];
            jokeVC.title = @"历史";
            [self.navigationController pushViewController:jokeVC animated:YES];
        }
            break;
            
        default:
            break;
    }
}

- (void)addRefresh {
    
    __weak typeof(self)weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [weakSelf.dataSource removeAllObjects];
        [weakSelf.cycleView.imgNameArray removeAllObjects];
        [weakSelf.tableView reloadData];
        
        [weakSelf analyticalData];
    }];
    
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
//        [weakSelf.dataSource removeAllObjects];
        NSInteger count = weakSelf.dataSource.count;
        weakSelf.start = [NSString stringWithFormat:@"%ld",count];
        [weakSelf analyticalData];
    }];
}
- (void)analyticalData {
    
    self.str = @"http://c.3g.163.com/nc/article/headline/T1348647909107/0-20.html?from=toutiao&size=20&passport=&devId=2vqQCWgxR7%2FxNM4EyVV6Aw%3D%3D&lat=&lon=&version=7.0&net=wifi&ts=1462501207&sign=0Y0Oh7WXbXvg%2F6S6pt7ccBD5Dxs6eLvJygsqTC1fyn548ErR02zJ6%2FKXOnxX046I&encryption=1&canal=miliao_news";
    [NetWorkRequestManager requestUrl:[NSURL URLWithString:self.str] RequestMethod:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            
            NSMutableDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSArray *array = jsonDic[@"T1348647909107"];
            
            NSDictionary *dict1 = array[0];
            NSArray *adsArray = dict1[@"ads"];
            
            NSMutableArray *imgArray = [NSMutableArray array];
            for (NSDictionary *adsDic in adsArray) {
                NSString *imgrc = adsDic[@"imgsrc"];
                [imgArray addObject:imgrc];
                
            }
            
            for (NSDictionary *itemDic in array) {
                ToutiaoModel *model = [ToutiaoModel modelWithDictionary:itemDic];
                [self.dataSource addObject:model];
                
            }
            
            
            NSLog(@"%ld",self.dataSource.count);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                
                self.cycleView.imgNameArray = imgArray;
                NSLog(@"%@",self.cycleView.imgNameArray);
                
                [[self.tableView defaultHeader]endRefreshing];
                [[self.tableView defaultFooter]endRefreshing];
            });
        }
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    
    return self.dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    UITableViewCell *cell = [ToutiaoModelCell cellWithTableView:tableView Model:self.dataSource[indexPath.row] IndexPath:indexPath];

    return cell;
  

   
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *modelName = NSStringFromClass([self.dataSource[indexPath.row] class]);
    Class cellClass = NSClassFromString([modelName stringByAppendingString:@"Cell"]);
    return [cellClass height];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
        ToutiaoModel *model = self.dataSource[indexPath.row];
        NSString *special = model.specialID;
        NSString *photo = model.photosetID;
        NSString *reSource = model.recSource;
        //    NSString *tag = model.TAG;
        //    NSString *video = model.videoID;
        if (special) {
            ToutiaoSpeciaTableController *specialTVC = [[ToutiaoSpeciaTableController alloc]init];
            specialTVC.specialID = model.specialID;
            specialTVC.navTitle = model.title;
            [self.navigationController pushViewController:specialTVC animated:YES];
        } else if (photo || [reSource isEqualToString:@"图集"]) {
            ToutiaoPhotoViewController *photoVC = [[ToutiaoPhotoViewController alloc]init];
            photoVC.navTitle = model.title;
            photoVC.photosetID = model.photosetID;
            NSLog(@"%@",model.photosetID);
            [self presentViewController:photoVC animated:YES completion:^{
                
            }];
        }
        else {
            ToutiaoArticleViewController *articalVC = [[ToutiaoArticleViewController alloc]init];
            articalVC.docid = model.docid;
            articalVC.navTitle = model.title;
            articalVC.model = model;
            [self.navigationController pushViewController:articalVC animated:YES];
        }

   

}

    


    




/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
